/**
 * 加密模块bcrypt的使用
  const bcrypt = require('bcryptjs')

  const enBcrypt = (value) => {
    // 另一种加密方式: 异步的情况下虽然await,但是内部还有一个异步,所以存储的还是明文(即awiat async函数内阻塞，函数外不阻塞)
    // await bcrypt.genSalt(10, (err, salt) => {
    //     bcrypt.hash(newUser.password, salt, (err, hash) => {
    //         if(err) throw err;
    //         newUser.password = hash;
    //     })
    // })

    // 解决办法: 使用同步方法
    const salt = bcrypt.genSaltSync(10);
    const hash = bcrypt.hashSync(value, salt)
    return hash
  }
  const deBcrypt = (ming, mi) {
    // 验证密码: await bcrypt.compareSync(明文, 密文)-返回值是布尔值
    return await bcrypt.compareSync(ming, mi)
  }
 */

const validator = require('validator');
const isErrorsEmpty = value => {
  return (
    value === undefined || value === null || (typeof value === "object" && Object.keys(value).length === 0) || (typeof value === "string" && value.trim().length === 0)
  )
}
const validateRegData = (data) => {
  let errors = {};
  data.username = !isErrorsEmpty(data.username) ? data.username : "";
  data.email = !isErrorsEmpty(data.email) ? data.email : "";
  data.phone = !isErrorsEmpty(data.phone) ? data.phone : "";
  data.password = !isErrorsEmpty(data.password) ? data.password : "";

  if (validator.isEmpty(data.username)) {
    errors.email = "用户名不能为空";
  }
  if (!validator.isLength(data.username, { min: 4, max: 10 })) {
    errors.username = "用户名的长度不能小于4位且不能超过10位"
  }
  if (validator.isEmpty(data.email)) {
    errors.email = "邮箱不能为空";
  }
  if (!validator.isEmail(data.email)) {
    errors.email = "邮箱格式不正确";
  }
  if (validator.isEmpty(data.phone)) {
    errors.phone = "手机号不能为空";
  }
  // if (!validator.isLength(data.username, { min: 4, max: 10 })) {
  //   errors.username = "手机号格式不正确"
  // }
  // equals两者是都相同
  if (!validator.isEmail(data.password)) {
    errors.password = "密码不能为空";
  }
  if (!validator.isLength(data.password, { min: 4, max: 10 })) {
    errors.password = "密码的长度不能小于4位且不能超过10位"
  }
  return {
    errors,
    isvalid: isErrorsEmpty(errors)
  }
}
const tools = {
  // enBcrypt,
  validateRegData
}

module.exports = tools
